package logo;

import java.awt.Container;
import java.awt.Dimension;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Logo extends JPanel {
	
	static final long SLEEPTIME = 15;
	private static final long serialVersionUID = 1L;

	Turtle _turtle;
	LogoPanel _panel;
	JFrame _frame;
	Parser _parser;
	private static Logo _singleton = null;
	
	final int _sizex = 800;
	final int _sizey = 600;
	
	public static Logo getLogo()
	{
		if (_singleton == null)
		{
			_singleton = new Logo();
		}
		return _singleton;
	}
	
	private List<String> getInputFileCommands()
	{
        List<String> lines = new ArrayList<String>();
		FileReader fileReader;
		try {
			fileReader = new FileReader("src\\logo\\test.txt");
	        BufferedReader bufferedReader = new BufferedReader(fileReader);
	        String line = null;
	        while ((line = bufferedReader.readLine()) != null) {
	            lines.add(line);
	        }
	        bufferedReader.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return lines;
	}
	
	public Logo()
	{
	}
	
	public static void sleep(long ms)
	{
		try { Thread.sleep(ms);} catch (InterruptedException e) {}
	}
	
	public static void sleep()
	{
		Logo.sleep(Logo.SLEEPTIME);
	}

	private void init()
	{
		List<String> textcommands = getInputFileCommands();
		_frame = new JFrame("Logo");
		_parser = new Parser(textcommands);
		_turtle = Turtle.getTurtle();
		_frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

		_panel = new LogoPanel(this);
		_panel.setMaximumSize(new Dimension(this._sizex, this._sizey));
		_panel.setMinimumSize(new Dimension(this._sizex, this._sizey));

		Container pane = _frame.getContentPane();

		pane.add(_panel);

		_frame.setVisible( true );
		_frame.pack();
		_frame.setSize( _sizex + 200, _sizey);
		_frame.setLocation(200, 200);
	}
	
	public void action(Turtle t, LogoPanel panel, Commands commands)
	{
		action(t, panel, commands, null);
	}

	public void action(Turtle t, LogoPanel panel, Commands commands, String name)
	{
		for (ICommand cmd: commands)
		{
			t.setGraphics(panel.getBufferedGraphics());
			cmd.action(t, panel, name);
			panel.repaint();
			Logo.sleep();
		}
	}
	
	public void work()
	{
		Logo.getLogo().action(_turtle, _panel, _parser.getCommands());
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Logo.getLogo().init();
		Logo.sleep(2500);
		Logo.getLogo().work();
	}
}
